package com.seeyon.apps.ext.kingdee.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.seeyon.apps.ext.kingdee.util.StringUtil;
import com.seeyon.cap.interfacetrace.util.JsonUtil;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.JDBCAgent;
import org.springframework.stereotype.Service;


@Service
public class kingdeeDaoImpl implements kingdeeDao{

	@Override
	public List<Object> geAttachment(String bizId, String docName, String docName2)
	{

		if (docName==null)
		{
			docName= "";
		}
		List<Object> result = new ArrayList<Object>();
		String sql = "SELECT DISTINCT * FROM TBL_SYS_ATTACHMENT where BIZ_ID=" + StringUtil.quoteSql(bizId)
				+ " OR DOC_NAME=" + StringUtil.quoteSql(docName);
				if (!StringUtil.isNULL(sql))
				{
					sql= sql + " OR DOC_NAME=" + StringUtil.quoteSql(docName2);
				}

		Connection connection = null;
		try
		{
			connection = JDBCAgent.getRawConnection();
			ResultSet resultSet = connection.createStatement().executeQuery(sql);
			ResultSetMetaData metaData = resultSet.getMetaData();
			while (resultSet.next()) {
				Map<String, Object> beanMap = new HashMap<String, Object>();
				for (int n = 1; n <= metaData.getColumnCount(); n++) {

					String field = StringUtil.underlineToCamel(metaData.getColumnLabel(n));
					Object value = OracleDialect.getResultSetValue(resultSet, n);
					beanMap.put(field, value);
				}
				result.add(beanMap);
			}

			resultSet.close();
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		} finally {
			try {
				if (connection!=null)
				{
					connection.close();
				}
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			}
		}
		return result;
	}

	@Override
	public Map<String, Object> geAttachmentFile(String attachmentId) {

		Map<String, Object> beanMap = new HashMap<String, Object>();
		final String sql = "SELECT DISTINCT * FROM TBL_SYS_ATTACHMENT where ATTACHMENT_ID=" + StringUtil.quoteSql(attachmentId) ;
		Connection connection = null;
		try
		{
			connection = JDBCAgent.getRawConnection();
			ResultSet resultSet = connection.createStatement().executeQuery(sql);
			ResultSetMetaData metaData = resultSet.getMetaData();
			if (resultSet.next()) {
				for (int n = 1; n <= metaData.getColumnCount(); n++) {
					String field = StringUtil.underlineToCamel(metaData.getColumnLabel(n));
					Object value = OracleDialect.getResultSetValue(resultSet, n);
					beanMap.put(field, value);
				}
			}
			resultSet.close();
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		} finally {
			try {
				if (connection!=null)
				{
					connection.close();
				}
			} catch (SQLException throwables) {
				throwables.printStackTrace();
			}
		}
		return beanMap;
	}
}